import { action, observable } from 'mobx';
import {
  getUserCfg,
  listLayoutCfg,
  getSecurityCfg,
  saveUserCfg,
  saveLayoutCfg,
  restoreDefaultLayoutCfg,
} from '../service';
import { message } from 'antd';

class AppStore {

  @observable userCfg = {};

  @observable layoutCfg = {};

  @observable securityCfg = {};

  /**
   * 析构函数
   */
  constructor() {
    this.listLayoutCfg();
    this.getUserCfg();
    this.getSecurityCfg();
  }

  async getUserCfg() {
    this.userCfg = await getUserCfg();
  }

  async listLayoutCfg() {
    this.layoutCfg = await listLayoutCfg();
    let topFirstLevelMenu = this.layoutCfg['layout.sider.topFirstLevelMenu'] == 'true' ? true : false;
    this.layoutCfg = { ...this.layoutCfg, 'layout.sider.topFirstLevelMenu': topFirstLevelMenu };
    this.form.setFieldsValue(this.layoutCfg);
  }

  async getSecurityCfg() {
    this.securityCfg = await getSecurityCfg();
  }

  @action
  async saveUserCfgHandler(data) {
    await saveUserCfg(data);
    message.info('保存用户信息成功');
  }

  @action
  async saveLayoutCfgHandler(data) {
    await saveLayoutCfg(data);
    await this.listLayoutCfg();
    window.parent.changeUserCfg(this.layoutCfg);
    message.info('保存系统布局成功');
  }

  @action
  async restoreDefaultLayoutCfgHandler() {
    await restoreDefaultLayoutCfg();
    await this.listLayoutCfg();
    window.parent.changeUserCfg(this.layoutCfg);
    message.info('恢复默认设置成功');
  }

  @action
  changeLayoutHandler(key) {
    this.layoutCfg.layout = key;
  }
}

export default AppStore;
